package com.centling.smartSealForPhone.activity

/**
 * Created by victor on 16-6-14.
 * activity管理类
 */
object AtyManager {
    private val activityList = arrayListOf<BaseActivity>()

    fun addActivity(activity: BaseActivity) {
        activityList.add(activity)
    }

    fun currentActivity(): BaseActivity? {
        return if (activityList.isEmpty()) null else activityList[activityList.lastIndex]
    }

    fun findActivity(clazz: Class<*>): BaseActivity? {
        var activity: BaseActivity? = null
        for (aty in activityList) {
            if (aty.javaClass == clazz) {
                activity = aty
                break
            }
        }
        return activity
    }

    fun removeActivity(activity: BaseActivity?) {
        activityList.remove(activity)
    }

    private fun finishActivity(activity: BaseActivity?) {
        if (activity != null) {
            activityList.remove(activity)
            activity.finish()
        }
    }

    fun finishActivity(clazz: Class<*>) {
        for (activity in activityList) {
            if (activity.javaClass == clazz) {
                finishActivity(activity)
            }
        }
    }

    fun finishAllActivitiesExcept(vararg clazz: Class<*>) {
        for (i in activityList.lastIndex downTo 0) {
            var shouldFinish = true
            clazz.forEach {
                if (activityList[i].javaClass == it) {
                    shouldFinish = false
                    return@forEach
                }
            }
            if (shouldFinish) {
                finishActivity(activityList[i])
            }
        }
    }

    fun finishAllActivities() {
        activityList.forEach {
            if (!it.isFinishing) {
                it.finish()
            }
        }
        activityList.clear()
    }
}